﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MetroDataApi.Models;
using Newtonsoft.Json;

namespace MetroDataApi.Controllers
{
    public class AfterMonitorPointsUploadController : ApiController
    {
        public HttpResponseMessage Get(int prjId, DateTime date)
        {
            using (var db = new MetroDataDataContext())
            {
                var summary = (from p in db.PreReviewMonitorPoints
                               where p.DateTime.Value == date && p.PrjId == prjId
                               join q in db.MonitorPointsDictionary
                               on p.PrjId equals q.PrjId into gs
                               from g in gs.DefaultIfEmpty()
                               where g != null && g.Name == p.Name
                               group g by new { g.MonitorType, g.Location }
                                   into gg
                                   select new
                                   {
                                       DateTime = date,
                                       Location = gg.Key.Location,
                                       MonitorType = gg.Key.MonitorType,
                                       PrjId = prjId
                                   }).ToList();

                var summaryList = from p in summary
                                  select new PointsSummaryNeedToBeReviewed()
                                      {
                                          DateTime = p.DateTime,
                                          Location = p.Location,
                                          MonitorType = p.MonitorType,
                                          PrjId = prjId
                                      };

                var existed = db.PointsSummaryNeedToBeReviewed.Where(p => p.PrjId == prjId && p.DateTime == date);

                db.PointsSummaryNeedToBeReviewed.DeleteAllOnSubmit(existed);
                db.PointsSummaryNeedToBeReviewed.InsertAllOnSubmit(summaryList);


                db.SubmitChanges();

                return Request.CreateResponse(HttpStatusCode.OK, summaryList, "application/json");
            }
        }
    }
}
